package au.org.htd.youslide.servlets;

import java.io.IOException;
import java.util.logging.Logger;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import au.org.htd.youslide.AppException;
import au.org.htd.youslide.Background;
import au.org.htd.youslide.PMF;
import au.org.htd.youslide.SongProject;

@SuppressWarnings("serial")
public class UploadServlet extends HttpServlet {
   private static final Logger log = Logger.getLogger(UploadServlet.class
         .getName());

   public void doGet(HttpServletRequest req, HttpServletResponse resp)
         throws IOException {
      String requestType = req.getParameter("requestType");
      try {
         if ("image_url".equals(requestType)) {
            doUploadImageByURL(req, resp);
         } else if ("attachment_url".equals(requestType)) {
            doUploadAttachmentByURL(req, resp);
         } else {
            log.info("NO REQUEST TYPE!!!");
         }
      } catch (AppException e) {
         log.info(e.getMessage());
         throw new IOException(e.getMessage());
      }
   }

   private void doUploadAttachmentByURL(HttpServletRequest req,
         HttpServletResponse resp) throws AppException {
      String id = req.getParameter("id");
      SongProject song = new SongProject(PMF.getPM()).get(Long.parseLong(id));
      try {
         resp.getWriter().write("" + song.attach(req.getParameter("url")));
      } catch (IOException e) {
         throw new AppException(e.getMessage());
      } finally {
         song.closeConnection();
      }
   }

   private void doUploadImageByURL(HttpServletRequest req,
         HttpServletResponse resp) throws AppException {
      Long id = Background.upload(req.getParameter("url")).getId();
      try {
         resp.getWriter().write(id.toString());
      } catch (IOException e) {
         throw new AppException(e.getMessage());
      }
   }
}
